package com.gang.ssm.bos.system.controller;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.gang.ssm.bos.common.Page;
import com.gang.ssm.bos.core.anotation.Permission;
import com.gang.ssm.bos.core.toolbox.ajax.AjaxResult;
import com.gang.ssm.bos.system.bean.Region;
import com.gang.ssm.bos.system.service.RegionService;

@RequestMapping("/region")
@Controller
public class RegionController extends BosController {
	
	@Autowired
	private RegionService regionService;

	@RequestMapping("/list")
	public String list(Page<Region> page, Map<String, Object> map) {
		regionService.pageQuery(page);
		map.put("page", page);
		return "system/base/regionList";
	}
	
	@RequestMapping("/region")
	public String input(Integer id, Map<String, Object> map) {
		if(id != null) {
			map.put("region", regionService.findById(id));
		}
		return "system/base/region";
	}
	
	@Permission({ADMIN})
	@ResponseBody
	@RequestMapping("/save")
	public AjaxResult save(Region region) {
		try {
			regionService.save(region);
			return success("保存成功!");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return fail("保存失败!");
	}
	
	@Permission({ADMIN})
	@ResponseBody
	@RequestMapping("/delete")
	public AjaxResult delete(Integer id) {
		try {
			regionService.deleteById(id);
			return success("删除成功!");
		} catch (Exception e) {
			e.printStackTrace();
			return fail("删除失败!");
		}
	}
	
	@ResponseBody
	@RequestMapping("/findAll")
	public AjaxResult findAll() {
		try {
			List<Region> regionList = regionService.findAll();
			return success(regionList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return fail("读取信息失败!");
	}
	
	/**
	 * 导入xls
	 * @param myFile
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/importXls")
	public AjaxResult importXls(MultipartFile myFile) {
		try {
			regionService.importXls(myFile);
			return success("导入成功!");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return fail("导入失败!");
	}
	
	/**
	 * 导出xls
	 */
	@RequestMapping("/exportXls")
	public void exportXls(HttpServletResponse response, 
			HttpServletRequest request){
		try {
			regionService.exportXls(response, request);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
